package com.wwj.code.util.captcha;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * @author admin007
 */
@Controller
@RequestMapping("captcha")
public class MyCaptchaUtils {


    @Autowired
    private RedisTemplate redisTemplate;


    @RequestMapping("getCaptcha")
    public void getCaptcha(HttpServletResponse response, String phone) {
        //定义图形验证码的长、宽、验证码字符数、干扰线宽度
        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(200, 100, 6, 15);

        Boolean aBoolean = redisTemplate.hasKey(phone);
        if (aBoolean == false) {
            try {
                redisTemplate.opsForValue().set(phone, captcha.getCode(), 60, TimeUnit.SECONDS);
                ServletOutputStream outputStream = response.getOutputStream();
                captcha.write(outputStream);
                outputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


}
